<!-- eslint-disable vue/html-self-closing -->
<template>
  <div v-loading="pageLoading" class="page-contaniner">
    <div class="page-content">
      <div class="page-title">
        <div class="main-top flex flex-aic">
          <div class="main-title">个人设置</div>
        </div>
      </div>
      <el-tabs v-model="activeName" class="el-tab-custom" type="card">
        <el-tab-pane label="基本信息" name="1">
          <el-row :gutter="64" style="width: 66%" class="mt-20">
            <el-col :span="24">
              <el-row :gutter="0">
                <div class="sub-title">基本信息</div>
              </el-row>
            </el-col>
            <el-col>
              <div class="page-form-content mt-20">
                <el-form
                  ref="form"
                  :model="formData"
                  :rules="rules"
                  label-width="100px"
                >
                  <template v-for="(item, index) in formList">
                    <el-form-item
                      :key="`${item.prop}${index}`"
                      :style="item.itemStyle || {}"
                      :label="item.name"
                      :prop="item.prop"
                      :class="item.itemClass"
                    >
                      <component
                        :is="item.componentType || 'el-input'"
                        v-if="item.prop"
                        v-model="formData[item.prop]"
                        :pop-data="formData"
                        :prop-key="item.prop"
                        :clearable="true"
                        v-bind="item.attrConfig || {}"
                        v-on="item.listenersConfig"
                        @changeImg="changeImg"
                      >
                        <template v-for="option in item.optionList">
                          <el-option
                            :key="option.code"
                            :label="option.name"
                            :value="option.code"
                          />
                        </template>
                      </component>
                    </el-form-item>
                  </template>
                </el-form>
              </div>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="密码修改" name="2">
          <el-row :gutter="64" style="width: 66%" class="mt-20">
            <el-col :span="24">
              <el-row :gutter="0">
                <div class="sub-title">密码修改</div>
              </el-row>
            </el-col>
            <el-col>
              <component
                :is="popData.popType"
                class="mt-20"
                :pop-data="popData.popData"
                :pop-config="popData.popConfig"
                :close="close"
                :confirm="confirm"
                @onFinish="onFinish"
                @initMenu="initMenu"
              />
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>

      <div
        class="page-form-footer flex flex-aic mt-20"
        style="width: 66%; margin-left: 100px"
      >
        <el-button
          v-for="(item, index) in btnList"
          :key="index"
          :type="item.type || ''"
          size="small"
          style="width: 144px"
          :loading="isLoading"
          @click="handleMethods(item.methods)"
        >{{ item.label }}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import EditPassword from '@/components/PopItems/edit-password'
import AddImg from '@/components/PopItems/add-img'
import store from '@/store'
// updateUserCenterInfo
export default {
  name: 'UserSetting',
  components: {
    EditPassword,
    AddImg
  },
  mixins: [dictMixin],
  data() {
    return {
      formData: {
        avatarUrl: null,
        fullName: null,
        mobilePhone: null,
        email: null,
        address: null
      },
      formList: [
        {
          name: '头像',
          prop: 'avatarUrl',
          componentType: 'AddImg',
          itemClass: 'width100p',
          attrConfig: { placeholder: '请上传头像' }
        },
        {
          name: '姓名',
          prop: 'fullName',
          itemStyle: { width: '50%' },
          attrConfig: { placeholder: '请输入姓名', maxlength: 64 }
        },
        {
          name: '手机号码',
          prop: 'mobilePhone',
          itemStyle: { width: '50%' },
          attrConfig: { placeholder: '请输入手机号码' }
        },
        {
          name: '邮箱',
          prop: 'email',
          itemStyle: { width: '50%' },
          attrConfig: { placeholder: '请输入邮箱' }
        },
        {
          name: '联系地址',
          prop: 'address',
          itemStyle: { width: '100%' },
          attrConfig: { placeholder: '请输入联系地址', maxlength: 500 },
          itemClass: 'width100p'
        }
      ],
      isLoading: false,
      pageLoading: false,

      // 弹窗数据
      popData: {
        popType: 'EditPassword',
        visible: true,
        popConfig: {
          overflow: 'auto',
          width: '500px'
        }
      },
      confirm: false,
      close: false,
      activeName: '1'
    }
  },
  computed: {
    rules() {
      return {
        fullName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { required: true, message: '姓名长度过长', max: 24, trigger: 'blur' }
        ],
        mobilePhone: [
          {
            required: false,
            trigger: 'blur',
            validator: this.mobilePhoneValidate
          }
        ],
        email: [
          { required: false, trigger: 'blur', validator: this.emailValidate }
        ]
      }
    },
    btnList() {
      return [
        {
          label: '取消',
          methods: 'cancaEdit'
        },
        {
          label: this.activeName === '1' ? '保存' : '确认修改',
          type: 'primary',
          methods: 'submitForm'
        }
      ]
    }
  },
  created() {
    this.queryUserInfo()
  },
  methods: {
    /** 查询当前用户信息 */
    async queryUserInfo() {
      try {
        this.pageLoading = true
        const res = await this.$api.getUserCenterInfo({})
        if (res.code === '1000') {
          const info = res.data || {}
          //   this.formData = { ...info }
          this.formList.forEach((e) => {
            this.$set(this.formData, e.prop, info[e.prop])
          })
        }
        this.pageLoading = false
      } catch (error) {
        this.pageLoading = false
      }
    },
    handleMethods(methods) {
      this[methods]()
    },
    cancaEdit() {
      this.$store.dispatch('tabs/closeTabs', '/home')
    },
    submitForm() {
      if (this.activeName === '1') {
        this.infoSubmit(this.formData)
      } else {
        this.confirm = !this.confirm
      }
    },
    /**
     * 提交
     */
    infoSubmit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.pageLoading = true
          // 上传新头像
          if (
            typeof this.formData.avatarUrl !== 'string' &&
            this.formData.avatarUrl
          ) {
            const formData = new FormData()
            formData.append('file', this.formData.avatarUrl.raw)
            const urlRes = await this.$api.fileManage.baseUploadData(
              '/customs-platform/grass-file/file/upload',
              formData
            )
            if (Number(urlRes.code) === 1000) {
              this.formData.avatarUrl = urlRes.data
              params.avatarUrl = urlRes.data
            }
          }
          const res = await this.$api.updateUserCenterInfo(params)
          this.pageLoading = false
          if (Number(res.code) === 1000) {
            this.$message.success('修改成功!')
            await store.dispatch('user/updateInfo')
            // TODO
            this.cancaEdit()
          }
        }
      })
    },
    /**
     * 弹窗确认
     */
    popConfirm() {
      this.confirm = !this.confirm
    },
    async initMenu() {
      this.popData.visible = false
      this.confirm = false
      this.popData.popType = ''
      this.$store.dispatch('tabs/setTabs', [])
      await store.dispatch('user/getInfo')
      this.$router.push('/')
    },
    /**
     * 弹窗确认请求成功
     */
    async onFinish(val) {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    },
    /** 上传头像 */
    changeImg(key, value) {
      this.$set(this.formData, 'avatarUrl', value)
    },
    /**  */
    /**
     * 验证手机号
     */
    mobilePhoneValidate(rule, value, callback) {
      const REP = new RegExp(/^1[3456789]\d{9}$/)
      if (value && !REP.test(value)) {
        callback(new Error('请输入正确的手机号码!'))
      } else {
        callback()
      }
    },
    /**
     * 验证邮箱
     */
    emailValidate(rule, value, callback) {
      const REP = new RegExp(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/)
      if (value && !REP.test(value)) {
        callback(new Error('请输入正确的邮箱格式!'))
      } else {
        callback()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/styles/pageCom.scss';
.tips > div {
  line-height: 32px;
}

.el-tab-custom {
  ::v-deep .el-tabs__header .el-tabs__nav-wrap {
    padding: 0 !important;
  }
  ::v-deep .el-tabs__item {
    height: auto;
    line-height: 32px;
  }
}
</style>
